package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.LearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 添加课程成功后MQ通知
 *
 * @author 蒼飞
 * @since 2023-07-24
 */
@Component
@Slf4j
@RequiredArgsConstructor//lombok提供的注解,在编译时添加构造函数实现依赖注入
public class LessonChangeListener {
    final LearningLessonService lessonService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.pay.queue",durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO order){
        //判断订单
        if(order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())){
            //如果订单有错
            log.info("接收到MQ消息有误,订单数据为空");
            return;
            //这里不能抛异常,不然MQ会一直重试
        }
        //添加订单
        log.info("监听到用户{}的订单{},需要添加课程{}到课表中",order.getUserId(),order.getOrderId(),order.getCourseIds());
        lessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }

}
